# -*- encoding: utf-8 -*-
"""
@author: acedar  
@time: 2025/3/30 16:57
@file: weather.py 
"""
import json
import httpx
from typing import Any
from mcp.server.fastmcp import FastMCP
from dotenv import load_dotenv
import os

load_dotenv()
mcp = FastMCP("weather")

# OpenWeather API 配置
# OPENWEATHER_API_BASE = "https://api.openweathermap.org/data/2.5/weather"
# API_KEY = "6fa113425c87105a796b21c51aaac9ad"  # 请替换为你自己的 OpenWeather API Key


API_KEY = os.environ.get("WEATHER_API_KEY")
API_BASE_URL = os.environ.get("WEATHER_BASE_URL")


async def get_weather(city: str) -> dict[str, Any] | None:
    params = {
        "q": city,
        "key": API_KEY,
        "aqi": "no"  # 关闭空气质量输入
    }

    async with httpx.AsyncClient() as client:
        try:
            print("API_BASE_URL", API_BASE_URL, params)
            response = await client.get(API_BASE_URL, params=params)
            return response.json()  # 返回字典类型
        except Exception as e:
            return {"error": f"请求失败: {str(e)}"}


def format_data(data: dict[str, Any] | str) -> str:
    """
    将天气数据格式化为易读文本。
    :param data: 天气数据（可以是字典或 JSON 字符串）
    :return: 格式化后的天气信息字符串
    """
    # 如果传入的是字符串，则先转换为字典
    if isinstance(data, str):
        try:
            data = json.loads(data)
        except Exception as e:
            return f"解析数据异常: {e}"

    """
    {'location': {
        'name': 'Shenzhen', 
        'region': 'Guangdong', 
        'country': 'China', 
        'lat': 22.5333, 
        'lon': 114.1333, 
        'tz_id': 'Asia/Hong_Kong', 
        'localtime_epoch': 1743328999, 
        'localtime': '2025-03-30 18:03'}, 
    'current': {
        'last_updated_epoch': 1743328800, 
        'last_updated': '2025-03-30 18:00', 
        'temp_c': 11.2, 
        'temp_f': 52.2, 
        'is_day': 1, 
        'condition': {
            'text': 'Partly cloudy', 
            'icon': '//cdn.weatherapi.com/weather/64x64/day/116.png', 
            'code': 1003
        }, 
        'wind_mph': 7.6, 
        'wind_kph': 12.2, 
        'wind_degree': 21, 
        'wind_dir': 'NNE', 
        'pressure_mb': 1020.0, 
        'pressure_in': 30.12, 'precip_mm': 0.06, 'precip_in': 0.0, 
        'humidity': 87, 'cloud': 75, 'feelslike_c': 9.7, 'feelslike_f': 49.5, 
        'windchill_c': 12.2, 'windchill_f': 53.9, 'heatindex_c': 13.2, 
        'heatindex_f': 55.8, 'dewpoint_c': 7.4, 'dewpoint_f': 45.3, 
        'vis_km': 8.0, 'vis_miles': 4.0, 'uv': 0.0, 'gust_mph': 9.3, 'gust_kph': 15.0}}

    """
    city = data.get("location", {}).get("name", "未知")
    country = data.get("location", {}).get("country", "未知")
    temp = data.get("current", {}).get("temp_c", "N/A")
    humidity = data.get("current", {}).get("humidity", "N/A")
    wind_speed = data.get("current", {}).get("wind_kph", "N/A")

    return (
        f"🌍 {city}, {country}\n"
        f"🌡 温度: {temp}°C\n"
        f"💧 湿度: {humidity}%\n"
        f"🌬 风速: {wind_speed} m/s\n"
    )


@mcp.tool()
async def query_weather(city: str) -> str:
    """
    输入指定城市的英文名称，返回今日天气查询结果。
    :param city: 城市名称（需使用英文）
    :return: 格式化后的天气信息
    """
    data = await get_weather(city)
    return format_data(data)


if __name__ == "__main__":
    # 以标准 I/O 方式运行 MCP 服务器
    mcp.run(transport='stdio')
